from datetime import datetime
from django.http import JsonResponse
from django.db import transaction
from django.shortcuts import render
from django.views.decorators.http import require_POST
from utils.decorators import login_required
from df_cart.models import Cart
from df_user.models import Address
from df_order.models import OrderBasic, OrderDetail
# Create your views here.


@login_required
@require_POST
def order_place(request):
    # 获取上传来的购物车内商品id的列表
    cart_id_list = request.POST.getlist('cart_id_list')

    # 根据商品id列表，获取购物车列表
    cart_list = Cart.objects.get_cart_list_by_cart_id_list(cart_id_list=cart_id_list)

    # 获取默认地址
    passport_id = request.session.get('passport_id')
    addr = Address.objects.get_one_address(passport_id=passport_id)

    cart_id_list = ','.join(cart_id_list)

    return render(request, 'df_order/place_order.html', {'cart_list': cart_list, 'addr': addr, 'cart_id_list':cart_id_list})


# /order/commit/
# 订单生成
@require_POST
@login_required
def order_commit(request):
    addr_id = request.POST.get('addr_id')
    pay_method = request.POST.get('pay_method')
    cart_id_list = request.POST.get('cart_id_list')

    passport_id = request.session.get('passport_id')

    # 组织订单基本信息数据
    # 订单号
    order_id = datetime.now().strftime('%Y%m%d%H%M%S')+str(passport_id)

    # 运费
    transit_price = 10

    # 计算商品的总数目和总价格
    cart_id_list = cart_id_list.split(',')

    print('cart_id_list:')
    print(cart_id_list)

    total_count, total_price = Cart.objects.get_amount_and_count_by_cart_id_list(cart_id_list=cart_id_list)

    # 设置一个保存点
    sid = transaction.savepoint()

    try:
        # 添加一个订单基本信息记录
        OrderBasic.objects.add_one_basic_info(order_id=order_id, passport_id=passport_id,
                                              addr_id=addr_id, total_count=total_count, total_price=total_price,
                                              transit_price=transit_price, pay_method=pay_method)
        for c in cart_id_list:
            print(c)

        # 获取购物车内商品列表
        cart_list = Cart.objects.get_cart_list_by_cart_id_list(cart_id_list=cart_id_list)

        # 组织订单详细信息记录
        for cart_info in cart_list:
            goods_id = cart_info.goods_id
            goods_count = cart_info.goods_count
            goods_price = cart_info.goods.goods_price

            # 库存充足
            if goods_count <= cart_info.goods.goods_stock:

                print('库存充足')
                # 添加一个详情记录
                OrderDetail.objects.add_one_detail_info(order_id=order_id, goods_id=goods_id,
                                                        goods_count=goods_count, goods_price=goods_price)

                # 更新库存和销量
                cart_info.goods.goods_stock -= goods_count       # 减少库存
                cart_info.goods.goods_sales += goods_count       # 增加销量

                print(cart_info.goods.goods_sales)
                print(cart_info.goods.goods_stock)

                cart_info.goods.save()

                # 删除购物车中的对应记录
                cart_info.delete()
            # 库存不足
            else:
                # 数据回滚
                transaction.savepoint_rollback(sid=sid)
                return JsonResponse({'res': 0})
    # 发生异常
    except:
         transaction.savepoint_rollback(sid=sid)
         return JsonResponse({'res': 2})

    # 订单成功
    transaction.savepoint_commit(sid=sid)
    return JsonResponse({'res': 1})
